<template>
  <div>
    <h3 class="titleH3">经销商归属</h3>
    <FormPanel
        :list="FormPanelList0"
        :cols="1"
        :labelWidth="120"
        :isSubmitBtn='false'
        :formType="type"
        ref="FormPanel"
        :collapse="false"
      ></FormPanel>
      <h3 class="titleH3">基本信息</h3>
      <FormPanel
        :list="FormPanelList"
        :cols="3"
        :labelWidth="120"
        :isSubmitBtn='false'
        :formType="type"
        ref="FormPanel1"
        :collapse="false"
      ></FormPanel>
      <h3 class="titleH3">授权品牌</h3>
      <FilterTable
        ref="table"
        :columns="columns"
        :dataSource="dataSource"
        :datakey="'records'"
        :isSelectColumn="true"
        :onColumnsChange="columns => this.columns = columns"
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" :disabled="type == 'show'?true:false" type="primary"       @click="addTable">新增</el-button>
        </template>
      </FilterTable>
      <div :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'center'
        }">
          <el-button size="small" type=""  @click="closeHandler">返回</el-button>
          <el-button size="small" v-show="type == 'show'?false:true" type="primary"  @click="saveHandle">保存</el-button>
      </div>

      <BaseDialog 
      :visible.sync="visible" 
      title="新增授权"
      width="30%"
      destroyOnClose>
        <FormPanel
          :list="FormPanelList2"
          :cols="1"
          :labelWidth="120"
          :isSubmitBtn='false'
          formType="edit"
          :collapse="false"
        ></FormPanel>
        <div :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'center'
        }">
          <el-button size="small" type=""  @click="cancal">返回</el-button>
          <el-button size="small" v-show="type == 'show'?false:true" type="primary"  @click="addSaveHandle">保存</el-button>
      </div>
    </BaseDialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import {addSaleInfoMaintain,
getDistributor,
addAuthorizedBrand,
getSeriesList,
deleteAuthorizedBrand,
updateSaleInfo,
queryAuthorizedById,
getOrgByOrgType,
getDistributorALL,
getMerge} from '@/api/common/CompanySale/dealerInfoMaintenance';
import * as types from '@/api/common/auth/roleManage/types';
import { IDNumber, phone,systemCode,numberCheck,banWord} from '@/utils/validate'
import { getBrandList, addModel ,getSeriesData} from '@/api/common/cars/brandcarsModels'
export default {
  name: 'modal',
  mixins: [dictionary],
  components: {
  },
  props:['rowData','type','listAllData'],
  data() {
    this.BaseTable = null;
    return {
        FormPanelList0:this.createFormPanelList0(),
        FormPanelList: this.createFormPanelList(),
        FormPanelList2:this.createFormPanelList2(),
        fetchApi:"",
        dataSource:[],
        fetchParams: {},
        columns: this.createTableColumns(),
        isShow: true,
        visible:false,
        province:[],
        dialogTitle:'',
        isHidden:70401002,
        dialogType:"",
        companyId:"",
    };
  },
  watch: {
    dataSource(){
      this.dataSource.forEach(x=>{
        //品牌
        getBrandList().then(res=>{
            if (res.resultCode === 200) {
              this.columns[3].editItems = res.data.map(x => ({ value: x.brandId, text: x.brandName }));
            }
        });
        
        
        //车系
        getSeriesData(x.brandId?x.brandId :"").then(res=>{
          if (res.resultCode === 200) {
            this.columns[4].editItems = res.data.map(x => ({ value: x.seriesId, text: x.seriesName }));
          }
        })
      })
      console.log(this.dataSource,"watc",this.columns)
    }
  },
  methods: {
      createFormPanelList0() {
        return [
          {
            type: 'SELECT',
            label: '所属经销商公司',
            fieldName: 'companyId',
            placeholder: '',
            disabled:false,
            style: { width: '240px' },
            itemList: [],
            change:val=>{
              console.log(val,"val")
              this.getArea(val)
            },
            rules: [{ required: true, message: '请选择所属经销商公司', trigger: 'change' }]
          }
        ];
      },
      createFormPanelList() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          disabled:false,
          placeholder: '',
          style: { width: '240px' },
          maxlength:8,
          rules: [{ required: true, message: '请选择', trigger: 'change' },
          { trigger: 'blur', validator: systemCode }]
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '',
          maxlength:32,
          style: { width: '240px' },
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '经销商简称',
          fieldName: 'dealerShortName',
          placeholder: '',
          maxlength:16,
          style: { width: '240px' },
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '经销商级别',
          fieldName: 'distributorLevel',
          placeholder: '',
          style: { width: '240px' },
          itemList: this.createDictList('2540'),
          rules: [{ required: true, message: '请选择市', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '经销商类型',
          fieldName: 'agType',
          placeholder: '',
          style: { width: '240px' },
          itemList: this.createDictList('2538'),
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '开票经销商',
          fieldName: 'taxNo',
          placeholder: '',
          maxlength:32,
          style: { width: '240px' },
        },
        {
          type: 'SELECT',
          label: '经销商状态',
          fieldName: 'validStatus',
          placeholder: '',
          style: { width: '240px' },
          itemList: this.createDictList('1001'),
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '经销商营业状态',
          fieldName: 'businessStatus',
          placeholder: '',
          style: { width: '240px' },
          itemList: this.createDictList('1011'),
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '传真',
          fieldName: 'faxNo',
          placeholder: '',
          maxlength:32,
          style: { width: '240px' },
        },
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'linkMan',
          placeholder: '',
          maxlength:8,
          style: { width: '240px' },
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '联系电话',
          fieldName: 'phone',
          placeholder: '',
          style: { width: '240px' },
          rules: [{ required: false, message: '请输入手机号码', trigger: 'blur' },
          { trigger: 'blur', validator: banWord }]
        },
        {
          type: 'INPUT',
          label: '邮编',
          fieldName: 'zipCode',
          placeholder: '',
          style: { width: '240px' },
          maxlength:6,
          rules: [{ required: false, message: '请选择', trigger: 'change' },
          { trigger: 'blur', validator: numberCheck }]
        },
        {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'saleArea',
          placeholder: '',
          style: { width: '240px' },
          // disabled:false,
          itemList: [],
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '省',
          fieldName: 'provinceId',
          placeholder: '',
          style: { width: '240px' },
          itemList: [],
          change:val=>{
            let city=[]
            if(val == 3662){
              this.FormPanelList[14].itemList=[{text:"台湾",value:3662}]
              this.FormPanelList[15].itemList=[{text:"台湾",value:3662}]
            }else if(val == 3663){
              this.FormPanelList[14].itemList=[{text:"香港",value:3663}]
              this.FormPanelList[15].itemList=[{text:"香港",value:3663}]
            }else if(val == 3664){
              this.FormPanelList[14].itemList=[{text:"澳门",value:3664}]
              this.FormPanelList[15].itemList=[{text:"澳门",value:3664}]
            }
            this.FormPanelList[14].initialValue=''
            this.FormPanelList[15].initialValue=''
            this.listAllData.forEach(x=>{
              // 筛选省
              if(x.parentRegionId == val){
                city.push({text:x.regionName,value:x.regionId})
                this.FormPanelList[14].itemList=_.uniqBy(city,'value')
              }
            })
          },
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '市',
          fieldName: 'cityId',
          placeholder: '',
          style: { width: '240px' },
          itemList: [],
          change:val=>{
            let county=[]
            this.FormPanelList[15].initialValue=''
            this.listAllData.forEach(x=>{
              // 筛选省
              if(x.parentRegionId == val){
                county.push({text:x.regionName,value:x.regionId})
                this.FormPanelList[15].itemList=_.uniqBy(county,'value')
              }
            })
          },
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '区/县',
          fieldName: 'countyId',
          placeholder: '',
          style: { width: '240px' },
          itemList: [],
        },
        {
          type: 'INPUT',
          label: '地址',
          fieldName: 'address',
          placeholder: '',
          style: { width: '240px' },
          maxlength:32,
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '经度',
          fieldName: 'latitude',
          placeholder: '',
          style: { width: '240px' },
          itemList: [],
          maxlength:16,
        },
        {
          type: 'INPUT',
          label: '纬度',
          fieldName: 'longitude',
          maxlength:16,
          placeholder: '',
          style: { width: '240px' },
        },
      ];
    },
    createFormPanelList2() {
        return [
          {
            type: 'SELECT',
            label: '授权类型',
            fieldName: 'billType',
            placeholder: '',
            style: { width: '240px' },
            itemList: [{ text: '品牌', value: 70401001 }, { text: '车系', value: 70401002 }],
            change:val=>{
              // this.isHidden=val
              if(val == 70401002){
                this.FormPanelList2[2].hidden=false
                this.FormPanelList2[0].initialValue=70401002
              }else{
                this.FormPanelList2[2].hidden=true
                this.FormPanelList2[0].initialValue=70401001
              }
            },
            rules: [{ required: true, message: '请选择授权类型', trigger: 'change' }]
          },
          {
            type: 'SELECT',
            label: '授权品牌',
            fieldName: 'brandId',
            placeholder: '',
            style: { width: '240px' },
            itemList:[],
            change:val=>{
                getSeriesList(val).then(res=>{
                  res.data.forEach(x=>{
                    this.FormPanelList2[2].itemList.push({text: x.name, value: x.carserialId })
                  })
                })
            },
            rules: [{ required: true, message: '请选择授权品牌', trigger: 'change' }]
          },
          {
            type: 'SELECT',
            label: '授权车系',
            fieldName: 'seriesId',
            placeholder: '',
            hidden:true,
            style: { width: '240px' },
            itemList: [],
            rules: [{ required: true, message: '请选择授权车系', trigger: 'change' }]
          }
        ];
      },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" disabled={this.type == 'show'?true:false} type="text" onClick={ ()=>this.deletFun(props.row) }>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
            title: '授权类型',
            dataIndex: 'billType',
            sorter: true,
            filterType: 'checkbox',
            filterItems: [{ text: '品牌', value: 70401001 }, { text: '车系', value: 70401002 }],
            editable: false,
            editType: 'select',
            editItems: [{ text: '品牌', value: 70401001 }, { text: '车系', value: 70401002 }],
            /* render: props => {
              return <span>{props.row.billType == 70401001?'品牌':'车系'}</span>;
            } */
        },
        {
            title: '授权品牌',
            dataIndex: 'brandId',
            sorter: true,
            filterType: 'checkbox',
            filterItems: [],
            editable: false,
            editType: 'select',
            editItems: [],
        },
        {
            title: '授权车系',
            dataIndex: 'seriesId',
            sorter: true,
            filterType: 'checkbox',
            filterItems: [],
            editable: false,
            editType: 'select',
            editItems: []
        }
      ];
    },
    async init(){
        this.getArea()
      if(this.type == 'edit'){
        this.FormPanelList0.find(x=>x.fieldName == 'companyId').disabled=true
        this.FormPanelList[0].disabled=true
        // this.FormPanelList[12].disabled=true
        this.fetchApi = queryAuthorizedById
        console.log(this.rowData,"编辑")
        this.FormPanelList0.find(x=>x.fieldName == 'companyId').itemList=[{ text: this.rowData.companyName, value: this.rowData.companyId}]
        /* getDistributorALL().then(res=>{
          console.log(res,"sss")
          res.data.forEach(x=>{
            this.FormPanelList0.find(x=>x.fieldName == 'companyId').itemList.push({ text: x.COMPANY_NAME_CN, value: x.COMPANY_ID })
          })
        }) */
      }else{
        getDistributor().then(res=>{
          res.data.forEach(x=>{
            this.FormPanelList0.find(x=>x.fieldName == 'companyId').itemList.push({ text: x.COMPANY_NAME_CN, value: x.COMPANY_ID })
          })
        })
        this.fetchApi =""
      }
      if(this.type == 'show'){
        this.FormPanelList0.find(x=>x.fieldName == 'companyId').itemList=[{ text: this.rowData.companyName, value: this.rowData.companyId}]
         /* getDistributorALL().then(res=>{
          console.log(res,"sss")
          res.data.forEach(x=>{
            this.FormPanelList0.find(x=>x.fieldName == 'companyId').itemList.push({ text: x.COMPANY_NAME_CN, value: x.COMPANY_ID })
          })
        }) */
      }
      this.FormPanelList0.find(x=>x.fieldName == 'companyId').initialValue=this.rowData.companyId
      this.FormPanelList.forEach(ele=>{
        ele.initialValue=this.rowData[ele.fieldName]
      })
      if(this.rowData.listOBSVO){
        this.dataSource = this.rowData.listOBSVO
        /* this.rowData.listOBSVO.forEach((x,k)=>{
          this.dataSource.push({
            index:k,
            })
        }) */
        
      }
      //初始化省市区赋值
        let initCity=[]
        let initCounty=[]
      this.listAllData.forEach(x=>{
        // 筛选省
        if(x.parentRegionId == null){
          this.province.push({text:x.regionName,value:x.regionId})
        }

        // 筛选市
        if(x.parentRegionId == this.FormPanelList[13].initialValue){
          initCity.push({text:x.regionName,value:x.regionId})
        }

        // 筛选区
        if(x.parentRegionId == this.FormPanelList[14].initialValue){
          initCounty.push({text:x.regionName,value:x.regionId})
        }
      })
      this.FormPanelList[13].itemList=_.uniqBy(this.province,'value')
      this.FormPanelList[14].itemList=_.uniqBy(initCity,'value')
      this.FormPanelList[15].itemList=_.uniqBy(initCounty,'value')
      if(this.type == 'add'){
        this.FormPanelList[14].itemList=[]
        this.FormPanelList[15].itemList=[]
      }
      console.log(this.columns,"columns")
      
    },
    //获取所属区域
    getArea(companyId){
      getMerge().then(res=>{
        console.log(res,"res")
        this.FormPanelList.find(item => item.fieldName === 'saleArea').itemList=[]
        if(res.data.isDisArea == 10041001){
          // 销售大区15061005
          getOrgByOrgType(15061005).then(res=>{
            console.log(res,"销售大区15061005")
            res.data.forEach(x=>{
              this.FormPanelList.find(item => item.fieldName === 'saleArea').itemList.push({ text: x.orgName, value: `${x.orgId}` })
            })
          })
        }else{
          //销售小区15061007
          getOrgByOrgType(15061007).then(res=>{
            console.log(res,"销售小区15061007")
            res.data.forEach(x=>{
              this.FormPanelList.find(item => item.fieldName === 'saleArea').itemList.push({ text: x.orgName, value: `${x.orgId}` })
            })
          })
        }
        
      })
    },
    getCookie(){
        let allCookie=document.cookie.split(';')
        allCookie.forEach(x=>{
          if(x.indexOf('dataType') > -1 ){
            this.dataType=x.split('=')[1]
            }
        })
        //判断是否为车厂10461003
        console.log(this.dataType,"dataType")
        if(this.dataType == 10461003){
          console.log(this.dataType,"车厂")
        }
      },
    // 新增
    async addTable(){
        await getBrandList().then(res=>{
          console.log(res,"品牌",this.columns1)
          this.FormPanelList2[1].itemList=[]
          res.data.forEach(x=>{
            this.FormPanelList2[1].itemList.push({text: x.brandName, value: x.brandId })
          })
        })
        this.visible=true
    },
    // 编辑
    /* async editFun(row) {
      console.log(row,"编辑")
      this.dialogType='edit'
      // await getBrandList().then(res=>{
      //   // console.log(res,"品牌",this.columns1)
      //   res.data.forEach(x=>{
      //     this.FormPanelList2[1].itemList.push({text: x.brandId, value: x.brandId })
      //   })
      // })
      this.visible=true
    }, */
    // 删除
    deletFun(row) {
      this.$confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          console.log(row)
          let rowArr=[]
          rowArr.push(row)
          this.$refs['table'].EXECUTE_DELETE(rowArr)
          // 重写序号
          this.dataSource.forEach((item,index) => {
            item.index = index
          })
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          /* const res = await deleteAuthorizedBrand(row.orgRelationId )
          if(res.errMsg) {
            this.$notify.error({title: '提示信息',message:res.errMsg||'删除失败!'});
          }else {
            this.$notify.success({title: '提示信息',message:'删除成功!'});
            // 重新加载
            this.fetchParams = { ...this.fetchParams };
          } */
        }).catch(() => {
          // this.$notify.info({title: '提示信息',message:'已取消删除'});
        });
    },
   
    // 保存
    saveHandle(){
      this.$refs.FormPanel.SUBMIT_FORM()
      let FormPanel1Data =  this.$refs.FormPanel1.SUBMIT_FORM()
      console.log(FormPanel1Data,"FormPanel1Data")
      //  || this.FormPanelList[0].initialValue || this.FormPanelList[1].initialValue || this.FormPanelList[2].initialValue || this.FormPanelList[3].initialValue || this.FormPanelList[4].initialValue || this.FormPanelList[6].initialValue|| this.FormPanelList[7].initialValue|| this.FormPanelList[9].initialValue|| this.FormPanelList[10].initialValue|| this.FormPanelList[12].initialValue|| this.FormPanelList[13].initialValue|| this.FormPanelList[14].initialValue|| this.FormPanelList[16].initialValue
      if(this.FormPanelList0.find(x=>x.fieldName == 'companyId').initialValue && FormPanel1Data){
        let addSaveParmas={
                billType:'',
                brandId:'',
                seriesId:'',
            }
            this.FormPanelList2.forEach(ele=>{
                Object.keys(addSaveParmas).forEach((x,k)=>{
                  if(x == ele.fieldName){
                    addSaveParmas[x] =ele.initialValue
                  }
                })
            })
         /*  if(this.FormPanelList2[0].initialValue){
            addSaveParmas.billType=this.FormPanelList2[0].initialValue == "车系"?70401001:70401002
          }  */ 
          
        let params={
          companyId:this.FormPanelList0.find(x=>x.fieldName == 'companyId').initialValue,
          // ...addSaveParmas,
          listOBSVO:[],
          "address": "string",
          "agType": 0,
          "businessStatus": 0,
          "cityId": 0,
          "countyId": 0,
          "dealerCode": "string",
          "dealerName": "string",
          "dealerShortName": "string",
          "distributorLevel": 0,
          "faxNo": "string",
          "latitude": "string",
          "linkMan": "string",
          "longitude": "string",
          "phone": "string",
          "provinceId": 0,
          "saleArea": "string",
          "taxNo": "string",
          "validStatus": 0,
          "zipCode": "string",
        }
        console.log(addSaveParmas,"addSaveParmas")
       params.listOBSVO = _.uniq(params.listOBSVO.concat(this.dataSource))
        this.FormPanelList.forEach(ele=>{
          Object.keys(params).forEach(x=>{
            if(x == ele.fieldName){
                params[x] =ele.initialValue
            }
            /* console.log(x,"车系x")
            if(x == "listOBSVO"){
              console.log(ele['billType'].initialValue,"车系id")
              params[x] = ele['billType'].initialValue== "车系"?70401001:70401002
            } */
          })
        })
        console.log(params,"新增")
        if(this.type == 'edit'){
          updateSaleInfo(params,this.rowData.dealerId).then(res=>{
            if(res.resultCode == 200){
                this.$notify.success({title: '提示信息',message:"保存成功"})
                this.closeHandler('refresh')
              }else{
                // this.$notify.error({title: '提示信息',message:res.errMsg})
              }
            })
        }else{
            addSaleInfoMaintain(params).then(res=>{
              if(res.resultCode == 200){
                this.$notify.success({title: '提示信息',message:"保存成功"})
                this.closeHandler('refresh')
              }else{
                // this.$notify.error({title: '提示信息',message:res.errMsg})
              }
            })
        }

        
      }
    },
    //新增保存
    addSaveHandle(){
      // console.log(this.FormPanelList2)
      let data=[]
      let addSaveParmas={
          index:"",
          billType:'',
          brandId:'',
          seriesId:'',
      }
      this.FormPanelList2.forEach(ele=>{
          Object.keys(addSaveParmas).forEach((x,k)=>{
            if(x == ele.fieldName){
              addSaveParmas[x] =ele.initialValue
            }
          })
      })
      addSaveParmas.billType=this.FormPanelList2[0].initialValue 
      data.push(addSaveParmas)
      data.forEach((x,k)=>{
        x.index = k
      })
      this.dataSource = _.uniq(this.dataSource.concat(data))
      // this.dataSource = _.uniq(this.dataSource.concat(this.dataSource.push(addSaveParmas)))
      this.visible=false
      console.log(this.dataSource,"dataSource")

      
        /* addAuthorizedBrand(addSaveParmas).then(res=>{
            if(res.resultCode == 200){
              this.$message({
                message: '保存成功',
                type: 'success'
              });
              this.fetchApi = queryAuthorizedById
              this.visible=false
              
              
            }else{
              this.$notify.error({title: '提示信息',message:res.errMsg})
            }
        }) */
    },
    // 新增返回
    cancal(){
      this.visible=false
    },
    closeHandler(type) {
        this.$emit('close',type)
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getCookie()
    this.init()
  }
};
</script>

<style lang="less" scoped>
.titleH3{
    height: 30px;
    line-height: 30px;
    margin-bottom: 5px;
    background: #eee;
    text-indent: 5px;
}
</style>
